package com.mycompany.delivery.validation;


import com.mycompany.delivery.dto.ContactDTO;
import org.springframework.stereotype.Component;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.boot.context.embedded.RegistrationBean;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * 
 * 
 *
 * @author Martin Horvath
 */
public class ContactSpringValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return ContactDTO.class.isAssignableFrom(clazz);
    }


    @Override
    public void validate(Object target, Errors e) {
        ContactDTO contact = (ContactDTO) target;

        ValidationUtils.rejectIfEmpty(e, "name", "contact.wrongName");
        ValidationUtils.rejectIfEmpty(e, "surname", "contact.wrongSurname");
        ValidationUtils.rejectIfEmpty(e, "street", "contact.wrongStreet");
        ValidationUtils.rejectIfEmpty(e, "city", "contact.wrongCity");
        ValidationUtils.rejectIfEmpty(e, "zip", "contact.wrongZip");
        ValidationUtils.rejectIfEmpty(e, "phone", "contact.wrongPhone");
        ValidationUtils.rejectIfEmpty(e, "email", "contact.wrongMail");
        
       if (!(contact.getName().matches("^[a-zA-Z]{2,20}$")) || contact.getName() == null || contact.getName().equals("")) {
            e.rejectValue("name", "contact.wrongName");
        }
        if (!(contact.getSurname().matches("^[a-zA-Z]{2,20}$")) || "".equals(contact.getSurname())) {               
                        e.rejectValue("surname", "contact.wrongSurname");
            }
  
        if ("".equals(contact.getCity()) || contact.getCity() == null) {               
                        e.rejectValue("city", "contact.wrongCity");
            }

        if ("".equals(contact.getStreet()) || contact.getCity() == null) {               
                        e.rejectValue("street", "contact.wrongStreet");
            }
        
        if ("".equals(contact.getZip()) || contact.getCity() == null) {               
                        e.rejectValue("zip", "contact.wrongZip");
            }
       
        if(!(contact.getEmail().matches("[a-zA-Z0-9_.]*@[a-zA-Z]*.[a-zA-Z]*")))
        {
            e.rejectValue("email", "contact.wrongMail");
        }
        if(!(contact.getPhone().matches("^[0-9+]{6,15}$")))
        {
            e.rejectValue("phone", "contact.wrongPhone");
        }

    }
}